package com.xsq.activity;

import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.common.utils.CommonUtils;
import com.xsq.BaseActivity;
import com.xsq.Constant;
import com.xsq.KeyBoardListener;
import com.xsq.PosMainActivity;
import com.xsq.R;
import com.xsq.URLConstant;
import com.xsq.util.HttpInterface;
import com.xsq.util.ServerUtils;

/**
 * 系统第一次设置系统信息页面
 * @author Administrator
 *
 */
@SuppressLint({ "SetJavaScriptEnabled", "HandlerLeak" })
public class GuideActivity extends BaseActivity {
	
	private  String setType = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.guide_main);

		preferences = getSharedPreferences(Constant.CACHE_XSQ_POS, MODE_PRIVATE);
		editor = preferences.edit();
		
		serverUtils = new ServerUtils(preferences, editor);
		hi = new HttpInterface(serverUtils);

		
		//setType = "";
		if(getServerInfo().equals("")){
			setType+="0,";
		}else{
			setType+="1,";
		}
		
		if(getPosNo().equals("") || getWinNo().equals("")){
			setType+="0";
		}else{
			setType+="1";
		}
		
		myWebView = (WebView) findViewById(R.id.webview);

		WebSettings webSettings = myWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setSupportZoom(false); // 支持缩放
		webSettings.setBuiltInZoomControls(false); // 显示放大缩小

		webSettings.setDefaultTextEncodingName("utf-8");
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 解决缓存问题
		myWebView.addJavascriptInterface(new DeviceOp(this), "appControl");
		myWebView.setWebViewClient(new MyWebViewClient());
		myWebView.setWebChromeClient(new MyWebChromeClient());

		myWebView.loadUrl(URLConstant.PAGE_WELCOME);
		
		KeyBoardListener.getInstance(this).init();

	}

	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
			AlertDialog.Builder b2 = new AlertDialog.Builder(GuideActivity.this).setTitle("提示：").setMessage(message)
					.setPositiveButton("ok", new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					});
			b2.setCancelable(false);
			b2.create();
			b2.show();
			return true;
		}
	}

	private class MyWebViewClient extends WebViewClient {
		/**
		 * 如果希望点击链接由自己处理，而不是新开Android的系统browser中响应该链接。
		 * 给WebView添加一个事件监听对象（WebViewClient)并重写其中的一些方法：
		 * shouldOverrideUrlLoading：对网页中超链接按钮的响应。当按下某个连接时
		 * WebViewClient会调用这个方法，并传递参数：按下的url。比如当webview内嵌
		 * 网页的某个数字被点击时，它会自动认为这是一个电话请求，会传递url：tel:123,
		 * 如果你不希望如此可通过重写shouldOverrideUrlLoading函数解决
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// 当开启新的页面的时候用webview来进行处理而不是用系统自带的浏览器处理
			// 互联网用：webView.loadUrl("http://www.google.com");
			// 本地文件用：webView.loadUrl("file:///android_asset/XX.html"); 本地文件存放
			view.loadUrl(url);
			return true;
		}

		/**
		 * 载入页面完成的事件
		 **/
		@Override
		public void onPageFinished(WebView view, String url) {
			// 获取网页内容
			// view.loadUrl("javascript:window.local_obj.showSource"+
			// "('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
			super.onPageFinished(view, url);
			String call = "javascript:pageInit('"+setType+"');";
			view.loadUrl(call);
		}

		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			// 这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。

			Toast.makeText(getApplicationContext(), "加载失败,请联系管理员", Toast.LENGTH_LONG).show();
		}
	}

	private static final int GO_HOME = 1000;

	private static final int SHOW_SUBMIT_POS_RESULT = 1009;
	private static final int SHOW_SUBMIT_TX_RESULT = 1008;
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GO_HOME:
				goHome();
				break;
			case SHOW_SUBMIT_TX_RESULT:
				showSubmitTxResult(msg);
				break;
			case SHOW_SUBMIT_POS_RESULT:
				showSubmitPosResult(msg);
				break;	
				
			}
		}
	};
	
	public void showSubmitPosResult(Message msg){
		
		hide_loading();
		String rs = msg.getData().getString("rs");
		String call = "javascript:showSubmitPosRs('"+rs+"');";
		
		myWebView.loadUrl(call);
	}
	
	public void showSubmitTxResult(Message msg){
		hide_loading();
		String rs = msg.getData().getString("rs");
		String call = "javascript:showSubmitTxRs('"+rs+"');";
		
		myWebView.loadUrl(call);
	}
	
	public void goHome(){
		Intent intent = new Intent(this, PosMainActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}


	private class DeviceOp {

		private Context mContext;

		public DeviceOp(Context c) {
			mContext = c;
		}

		@JavascriptInterface
		public String doTest() {
			Toast.makeText(mContext, "test ... test", Toast.LENGTH_SHORT).show();
			return "1";
		}

		
		
		@JavascriptInterface
		public void goIndex() {
			
			mHandler.sendEmptyMessage(GO_HOME);
		}
		
		
		@JavascriptInterface
		public String doTxConfig(final String serverIp1,final String port1,final String serverIp2,final String port2) {

			try{
				
				show_loading("正在验证服务器可用性并保存...");
				Constant.threadPoolExecutor.execute(new Runnable() {
					
					public void run() {
						
						String rs = "";
						if (serverIp1 == null || serverIp1.trim().equals("")  ||port1 == null || port1.trim().equals("") ) {
							//必选参数为空或者参数格式不对
							rs =  "-1";
						} else {
							boolean hasBak = false;
							if(serverIp2!=null && !serverIp2.equals("") && port2!=null && !port2.equals("")  &&  !(serverIp2.equals(serverIp1) && port1.equals(port2))){
								hasBak = true;
							}
							//参数格式验证
							
							String server = serverIp1+":"+port1;
							//数据后台验证
							Map<String,Object> testResult = hi.testServer(server, "test", "test");
							String validResult = "";
							
							validResult+=String.valueOf(testResult.get("is_success"));
							
							//保存进入缓存
							serverUtils.setServer(server, String.valueOf(testResult.get("is_success")));
							
							if(hasBak){
								validResult+=",";
								String server2 = serverIp2+":"+port2;
								//数据后台验证
								Map<String,Object> testResult2 = hi.testServer(server2, "test", "test");
								validResult+=String.valueOf(testResult2.get("is_success"));
								
								serverUtils.setServer(server2, String.valueOf(testResult.get("is_success")));
							}
							
							rs =  validResult;
							
							Message message = new Message();
							message.what = SHOW_SUBMIT_TX_RESULT;
							Bundle bundle = new Bundle();
							bundle.putString("rs", rs);
							message.setData(bundle);
							
							mHandler.sendMessage(message);
						}
						
					}
				});
				
			
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		
		@JavascriptInterface
		public String doPosConfig(final String posno,final String winno) {

			try{
				show_loading("正在提交数据...");
				
				Constant.threadPoolExecutor.execute(new Runnable() {
					
					public void run() {
						
						String rs = "";
						if (posno == null || posno.trim().equals("") || winno == null || winno.trim().equals("") ) {
							//必选参数为空
							rs =  "-1";
						} else {
							
							//参数格式验证
						
							//数据后台验证
							Map<String,Object> result = hi.validatePosParam(posno, getDeviceId(), winno);
							
							if(String.valueOf(result.get("is_success")).equals("1")){
								editor.putString(Constant.CACHE_POSNO, posno);
								editor.putString(Constant.CACHE_WINNO, winno);
								
								editor.putString(Constant.CACHE_WINNAME, String.valueOf(result.get("winname")));
								editor.putString(Constant.CACHE_MERCHANT, String.valueOf(result.get("merchantname")));
								//消费限额:分
								editor.putString(Constant.CACHE_XFXX, String.valueOf(result.get("xfxe")));
								
								editor.commit();
							}
							if(String.valueOf(result.get("is_success")).equals("0") ){
								rs =  String.valueOf(result.get("error_msg"));
							}else{
								rs = String.valueOf(result.get("is_success"));
							}
							
							
						}
						
						
						Message message = new Message();
						message.what = SHOW_SUBMIT_POS_RESULT;
						Bundle bundle = new Bundle();
						bundle.putString("rs", rs);
						message.setData(bundle);
						
						mHandler.sendMessage(message);
					}
				});
				
				
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}
		

	}

	
	
	 public static int counter = 0;
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
       	 	counter++;
			new Handler().postDelayed(new Runnable() {
				public void run() {
					counter--;
				}
			}, 3 * 1000);
			if (counter > 1) {
				 CommonUtils.Exit(this);  
				  
			} else {
				Toast.makeText(GuideActivity.this, "再次点击退出应用", Toast.LENGTH_SHORT).show();
			}
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
